package com.zzyl.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.DeviceDataPageQueryDto;
import com.zzyl.entity.DeviceData;
import com.zzyl.mapper.DeviceDataMapper;
import com.zzyl.service.DeviceDataService;
import com.zzyl.vo.DeviceDataGraphVo;
import com.zzyl.vo.DeviceDataVo;
import com.zzyl.vo.DeviceVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeviceDataServiceImpl implements DeviceDataService {

    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Override
    public PageResponse<DeviceDataVo> getDeviceDataPage(DeviceDataPageQueryDto pageQueryDto) {
        PageHelper.startPage(pageQueryDto.getPageNum(),pageQueryDto.getPageSize());
        pageQueryDto.setEndDate(LocalDateTimeUtil.of(pageQueryDto.getEndTime()));
        pageQueryDto.setStartDate(LocalDateTimeUtil.of(pageQueryDto.getStartTime()));
        Page page = (Page) deviceDataMapper.selectByPage(pageQueryDto);
        PageResponse<DeviceDataVo> of = PageResponse.of(page, DeviceDataVo.class);
        return of;
    }

    @Override
    public List<DeviceDataGraphVo> queryDeviceDataListByDay(String iotId, Long startTime, Long endTime, String functionId) {
        LocalDateTime startDate = LocalDateTimeUtil.of(startTime);
        LocalDateTime endDate = LocalDateTimeUtil.of(endTime);
        List<DeviceDataGraphVo> list = deviceDataMapper.queryDeviceDataListByDay(iotId,startDate,endDate,functionId);
        List<DeviceDataGraphVo> list1 = DeviceDataGraphVo.dayInstance(startDate);
        list.forEach(deviceDataGraphVo -> {
            list1.forEach(deviceDataGraphVo1 -> {
                if(deviceDataGraphVo.getDateTime().equals(deviceDataGraphVo1.getDateTime())){
                    deviceDataGraphVo1.setDataValue(deviceDataGraphVo.getDataValue());
                }
            });
        });
        return list1;
    }

    @Override
    public List<DeviceDataGraphVo> queryDeviceDataListByWeek(String iotId, Long startTime, Long endTime, String functionId) {
        LocalDateTime startDate = LocalDateTimeUtil.of(startTime);
        LocalDateTime endDate = LocalDateTimeUtil.of(endTime);
        List<DeviceDataGraphVo> list = deviceDataMapper.queryDeviceDataListByWeek(iotId,startDate,endDate,functionId);
        List<DeviceDataGraphVo> list1 = DeviceDataGraphVo.weekInstance(startDate);
        list.forEach(deviceDataGraphVo -> {
            list1.forEach(deviceDataGraphVo1 -> {
                if(deviceDataGraphVo.getDateTime().equals(deviceDataGraphVo1.getDateTime())){
                    deviceDataGraphVo1.setDataValue(deviceDataGraphVo.getDataValue());
                }
            });
        });
        return list1;
    }
}
